/**
 * 作者:hanbo
 * 日期:2019/1/3011:26
 * 描述:
 */

/**
 * 下载文件
 * @param url {String}文件下载网址
 * @param path {String}文件保存路径
 * @param name {String}文件保存名称
 */
    //文件下载
const fs = require("fs");
const path = require("path");
const request = require("request");
const mkdirp = require("mkdirp");
const userAgents = require('./userAgents');

function downFile(url, savePath, saveName, callBack) {
    const filePath = path.join(savePath, saveName);
    if (!fs.existsSync(savePath)) {//判断文件夹是否存在
        mkdirp(savePath, function (err) {
            if (err) {
                console.error(err);
                callBack(2);
            } else {
                downAndSave(url, filePath,callBack)
            }
        });

    } else if (!fs.existsSync(filePath)) {//判断文件是否存在
        downAndSave(url, filePath,callBack)
    }else {
        callBack(3)
    }

    function downAndSave(url, filePath,callBack) {
        let userAgent = userAgents[parseInt(Math.random() * userAgents.length)];
        let stream = fs.createWriteStream(filePath);
        let downProgress = request({url: url, headers: {'User-Agent': userAgent}}).pipe(stream);
        downProgress.on("close", function (err) {
            if (err) {
                console.log("down fail");
            } else {
                callBack(0);
            }
        });
        downProgress.on('error', function (err) {
            console.log("错误信息:" + err);
            callBack(1);
        })
    }
}


function getCurrentUrl(mapInfo, x, y, z) {
    //需要在以后改进正则，匹配大小写
    let result = mapInfo.url.replace("{x}", x);
    result = result.replace("{y}", y);
    result = result.replace("{z}", z);
    if (mapInfo.key) {
        result = result.replace("{key}", mapInfo.key);
    }
    if (mapInfo.subdomains) {
        let index = Math.round(Math.random() * ((mapInfo.subdomains.length - 1)));
        result = result.replace("{s}", mapInfo.subdomains[index]);
    }
    return result;
}

function clearAll(path,callBack){
    
    function delDir(path) {
        let files = [];
        if(fs.existsSync(path)){
            files = fs.readdirSync(path);
            files.forEach((file, index) => {
                console.log("delete"+path);
                let curPath = path + "/" + file;
                if(fs.statSync(curPath).isDirectory()){
                    delDir(curPath); //递归删除文件夹
                } else {
                    fs.unlinkSync(curPath); //删除文件
                }
            });
            fs.rmdirSync(path);

        }else {
            console.log(2);
        }
    }
    delDir(path);
    mkdirp(path, function (err) {
        if (err) {
          console.log(err)
        }
    });
    callBack();
}

exports.downFile = downFile;
exports.getCurrentUrl = getCurrentUrl;
exports.clearAll = clearAll;